/*******************************************************************************
 * Copyright (c) 2005, 2014 springside.github.io
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 *******************************************************************************/
package cn.com.digitalnet.ad.service;

import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import cn.com.digitalnet.ad.base.CrudService;
import cn.com.digitalnet.ad.entity.Permission;
import cn.com.digitalnet.ad.entity.Role;
import cn.com.digitalnet.ad.entity.User;
import cn.com.digitalnet.ad.repository.mybatis.CrudMao;
import cn.com.digitalnet.ad.repository.mybatis.RoleMao;

import com.google.common.collect.Maps;

// Spring Bean的标识.
@Component
// 类中所有public函数都纳入事务管理的标识.
@Transactional
public class RoleService extends CrudService<Role>{

	@Autowired private RoleMao mao;

	@Override
	protected CrudMao<Role> mao() {
		return mao;
	}

	@Override
	public void save(Role role) {
		mao.save(role);

		//添加新权限
		for(Permission p : role.getPermissionList()){
			Map<String, Object> params = Maps.newHashMap();
			params.put("roleId", role.getId());
			params.put("permissionId", p.getId());
			mao.addPermissionForRole(params);
		}
	}
	
	@Override
	public void update(Role role) {
		mao.update(role);
		
		//清除原有权限
		mao.cleanPermissionsForRole(role.getId());

		//添加新权限
		for(Permission p : role.getPermissionList()){
			Map<String, Object> params = Maps.newHashMap();
			params.put("roleId", role.getId());
			params.put("permissionId", p.getId());
			mao.addPermissionForRole(params);
		}
	}

	/**
	 * 返回角色及其权限集合
	 * @author qidafang
	 */
	public Role findOneWithPermissions(Long id){
		Role r = super.findOne(id);
		List<Permission> permissions = mao.getPermissionsForRole(id);
		r.setPermissionList(permissions);
		return r;
	}
	
}
